<template>
  <div class="comment-system">
    <!-- 评论输入区 -->
    <div v-if="allowComment" class="comment-input-section">
      <div class="comment-input-container">
        <div class="user-avatar">
          <img
            v-if="currentUser?.avatar"
            :alt="currentUser.name"
            :src="currentUser.avatar"
          />
          <div v-else class="avatar-placeholder">
            {{ currentUser?.name?.charAt(0) || '我' }}
          </div>
        </div>

        <div class="input-wrapper">
          <div class="input-area">
            <textarea
              ref="commentInputRef"
              v-model="newComment"
              :placeholder="replyTarget ? `回复 @${replyTarget.user.name}：` : '写下您的想法...'"
              class="comment-textarea"
              maxlength="500"
              rows="3"
              @input="handleInput"
              @keydown.ctrl.enter="submitComment"
            ></textarea>

            <div class="input-tools">
              <div class="emoji-picker">
                <button class="tool-btn" @click="showEmojiPicker = !showEmojiPicker">
                  <svg fill="none" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                    <path d="M8 14s1.5 2 4 2 4-2 4-2" stroke="currentColor" stroke-width="2"/>
                    <line stroke="currentColor" stroke-width="2" x1="9" x2="9.01" y1="9" y2="9"/>
                    <line stroke="currentColor" stroke-width="2" x1="15" x2="15.01" y1="9" y2="9"/>
                  </svg>
                </button>

                <div v-if="showEmojiPicker" class="emoji-panel" @click.stop>
                  <div class="emoji-categories">
                    <button
                      v-for="category in emojiCategories"
                      :key="category.name"
                      :class="{ active: activeCategory === category.name }"
                      class="category-btn"
                      @click="activeCategory = category.name"
                    >
                      {{ category.icon }}
                    </button>
                  </div>
                  <div class="emoji-grid">
                    <button
                      v-for="emoji in currentEmojis"
                      :key="emoji"
                      class="emoji-btn"
                      @click="insertEmoji(emoji)"
                    >
                      {{ emoji }}
                    </button>
                  </div>
                </div>
              </div>

              <div v-if="showMentions" class="mention-users">
                <div class="mention-list">
                  <div
                    v-for="user in mentionSuggestions"
                    :key="user.id"
                    class="mention-item"
                    @click="insertMention(user)"
                  >
                    <div class="mention-avatar">
                      <img v-if="user.avatar" :alt="user.name" :src="user.avatar" />
                      <div v-else class="avatar-placeholder">{{ user.name.charAt(0) }}</div>
                    </div>
                    <div class="mention-info">
                      <div class="mention-name">{{ user.name }}</div>
                      <div class="mention-relation">{{ user.relation }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="input-actions">
            <div class="input-stats">
              <span :class="{ warning: newComment.length > 450 }" class="char-count">
                {{ newComment.length }}/500
              </span>
              <span v-if="replyTarget" class="reply-info">
                回复 @{{ replyTarget.user.name }}
                <button class="cancel-reply" @click="cancelReply">✕</button>
              </span>
            </div>

            <div class="action-buttons">
              <button
                v-if="newComment.trim() || replyTarget"
                class="cancel-btn"
                @click="clearInput"
              >
                取消
              </button>
              <button
                :disabled="!newComment.trim() || isSubmitting"
                class="submit-btn"
                @click="submitComment"
              >
                <svg v-if="isSubmitting" class="loading-spinner" fill="none" viewBox="0 0 24 24">
                  <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                </svg>
                <svg v-else fill="none" viewBox="0 0 24 24">
                  <line stroke="currentColor" stroke-width="2" x1="22" x2="11" y1="2" y2="13"/>
                  <polygon fill="currentColor" points="22,2 15,22 11,13 2,9 22,2"/>
                </svg>
                {{ isSubmitting ? '发送中...' : '发送' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论排序和筛选 -->
    <div v-if="comments.length > 0" class="comment-controls">
      <div class="comment-stats">
        <span class="comment-count">{{ totalComments }} 条评论</span>
      </div>

      <div class="comment-filters">
        <select v-model="sortBy" class="sort-select" @change="handleSortChange">
          <option value="newest">最新</option>
          <option value="oldest">最早</option>
          <option value="hottest">最热</option>
        </select>

        <button
          :class="{ active: onlyShowImages }"
          class="filter-btn"
          @click="onlyShowImages = !onlyShowImages"
        >
          <svg fill="none" viewBox="0 0 24 24">
            <rect height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="3"/>
            <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2"/>
            <polyline points="21,15 16,10 5,21" stroke="currentColor" stroke-width="2"/>
          </svg>
          图片评论
        </button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="filteredComments.length > 0" class="comments-container">
      <div class="comments-list">
        <div
          v-for="comment in filteredComments"
          :key="comment.id"
          :class="{
            'is-replying': replyTarget?.id === comment.id,
            'is-highlighted': highlightCommentId === comment.id
          }"
          class="comment-item"
        >
          <!-- 评论头像 -->
          <div class="comment-avatar">
            <img
              v-if="comment.user.avatar"
              :alt="comment.user.name"
              :src="comment.user.avatar"
            />
            <div v-else class="avatar-placeholder">
              {{ comment.user.name.charAt(0) }}
            </div>
          </div>

          <!-- 评论内容 -->
          <div class="comment-content">
            <div class="comment-header">
              <div class="comment-author">{{ comment.user.name }}</div>
              <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
              <div v-if="!comment.isDeleted" class="comment-actions">
                <button class="action-btn" @click="toggleCommentMenu(comment)">
                  <svg fill="none" viewBox="0 0 24 24">
                    <circle cx="12" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                    <circle cx="19" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                    <circle cx="5" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                  </svg>
                </button>

                <!-- 评论操作菜单 -->
                <div v-if="activeCommentMenu === comment.id" class="comment-menu">
                  <button class="menu-item" @click="replyToComment(comment)">
                    <svg fill="none" viewBox="0 0 24 24">
                      <polyline points="9,17 4,12 9,7" stroke="currentColor" stroke-width="2"/>
                      <path d="M20 18v-2a4 4 0 0 0-4-4H4" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    回复
                  </button>
                  <button class="menu-item" @click="copyComment(comment)">
                    <svg fill="none" viewBox="0 0 24 24">
                      <rect height="13" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="13" x="9" y="9"/>
                      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    复制
                  </button>
                  <button
                    v-if="comment.user.id === currentUser?.id"
                    class="menu-item"
                    @click="deleteComment(comment)"
                  >
                    <svg fill="none" viewBox="0 0 24 24">
                      <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2"/>
                      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    删除
                  </button>
                  <button class="menu-item danger" @click="reportComment(comment)">
                    <svg fill="none" viewBox="0 0 24 24">
                      <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                      <line stroke="currentColor" stroke-width="2" x1="12" x2="12" y1="8" y2="12"/>
                      <line stroke="currentColor" stroke-width="2" x1="12" x2="12.01" y1="16" y2="16"/>
                    </svg>
                    举报
                  </button>
                </div>
              </div>
            </div>

            <!-- 评论文本内容 -->
            <div v-if="!comment.isDeleted" class="comment-text">
              <span v-html="formatCommentContent(comment.content)"></span>
            </div>

            <!-- 已删除状态 -->
            <div v-else class="comment-deleted">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                <line stroke="currentColor" stroke-width="2" x1="12" x2="12" y1="8" y2="12"/>
                <line stroke="currentColor" stroke-width="2" x1="12" x2="12.01" y1="16" y2="16"/>
              </svg>
              此评论已被删除
            </div>

            <!-- 评论图片 -->
            <div v-if="comment.images && comment.images.length > 0" class="comment-images">
              <div
                v-for="(image, index) in comment.images"
                :key="index"
                class="comment-image"
                @click="previewImage(image, comment.images)"
              >
                <img :alt="image.description" :src="image.thumbnail || image.url" />
              </div>
            </div>

            <!-- 评论互动按钮 -->
            <div v-if="!comment.isDeleted" class="comment-interactions">
              <button
                :class="{ active: comment.isLiked }"
                class="interaction-btn like-btn"
                @click="toggleCommentLike(comment)"
              >
                <svg fill="none" viewBox="0 0 24 24">
                  <path :fill="comment.isLiked ? 'currentColor' : 'none'"
                        d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"
                        stroke="currentColor"
                        stroke-width="2"/>
                </svg>
                {{ comment.likeCount > 0 ? comment.likeCount : '赞' }}
              </button>

              <button class="interaction-btn reply-btn" @click="replyToComment(comment)">
                <svg fill="none" viewBox="0 0 24 24">
                  <polyline points="9,17 4,12 9,7" stroke="currentColor" stroke-width="2"/>
                  <path d="M20 18v-2a4 4 0 0 0-4-4H4" stroke="currentColor" stroke-width="2"/>
                </svg>
                回复
              </button>

              <!-- 快速表情回应 -->
              <div class="quick-reactions">
                <button
                  v-for="reaction in quickReactions"
                  :key="reaction.emoji"
                  :class="{ active: comment.userReaction === reaction.emoji }"
                  class="reaction-btn"
                  @click="addReaction(comment, reaction.emoji)"
                >
                  {{ reaction.emoji }}
                  <span v-if="comment.reactions && comment.reactions[reaction.emoji]">
                    {{ comment.reactions[reaction.emoji] }}
                  </span>
                </button>
              </div>
            </div>

            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="replies-container">
              <div class="replies-header">
                <button
                  class="toggle-replies"
                  @click="toggleReplies(comment.id)"
                >
                  <svg
                    :class="{ 'rotated': expandedReplies.has(comment.id) }"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <polyline points="6,9 12,15 18,9" stroke="currentColor" stroke-width="2"/>
                  </svg>
                  {{ expandedReplies.has(comment.id) ? '收起' : '展开' }} {{ comment.replies.length }} 条回复
                </button>
              </div>

              <div
                v-if="expandedReplies.has(comment.id)"
                class="replies-list"
              >
                <div
                  v-for="reply in comment.replies"
                  :key="reply.id"
                  class="reply-item"
                >
                  <div class="reply-avatar">
                    <img
                      v-if="reply.user.avatar"
                      :alt="reply.user.name"
                      :src="reply.user.avatar"
                    />
                    <div v-else class="avatar-placeholder">
                      {{ reply.user.name.charAt(0) }}
                    </div>
                  </div>

                  <div class="reply-content">
                    <div class="reply-header">
                      <span class="reply-author">{{ reply.user.name }}</span>
                      <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                    </div>
                    <div class="reply-text" v-html="formatCommentContent(reply.content)"></div>

                    <div class="reply-actions">
                      <button
                        :class="{ active: reply.isLiked }"
                        class="reply-action like"
                        @click="toggleReplyLike(reply)"
                      >
                        <svg fill="none" viewBox="0 0 24 24">
                          <path :fill="reply.isLiked ? 'currentColor' : 'none'"
                                d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"
                                stroke="currentColor"
                                stroke-width="2"/>
                        </svg>
                        {{ reply.likeCount || '' }}
                      </button>
                      <button class="reply-action" @click="replyToComment(comment, reply)">
                        回复
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMore && !loading" class="load-more-section">
        <button class="load-more-btn" @click="loadMoreComments">
          加载更多评论
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-comments">
      <svg fill="none" viewBox="0 0 24 24">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" stroke-width="2"/>
      </svg>
      <p>{{ allowComment ? '还没有评论，快来说两句吧！' : '评论功能已关闭' }}</p>
    </div>

    <!-- 图片预览 -->
    <div v-if="showImagePreview" class="image-preview-overlay" @click.self="closeImagePreview">
      <div class="image-preview-container">
        <button class="preview-close" @click="closeImagePreview">
          <svg fill="none" viewBox="0 0 24 24">
            <line stroke="currentColor" stroke-width="2" x1="18" x2="6" y1="6" y2="18"/>
            <line stroke="currentColor" stroke-width="2" x1="6" x2="18" y1="6" y2="18"/>
          </svg>
        </button>

        <img v-if="currentPreviewImage" :alt="currentPreviewImage.description" :src="currentPreviewImage.url" />

        <div v-if="previewImages.length > 1" class="preview-controls">
          <button class="preview-nav prev" @click="previousImage">
            <svg fill="none" viewBox="0 0 24 24">
              <polyline points="15,18 9,12 15,6" stroke="currentColor" stroke-width="2"/>
            </svg>
          </button>
          <button class="preview-nav next" @click="nextImage">
            <svg fill="none" viewBox="0 0 24 24">
              <polyline points="9,18 15,12 9,6" stroke="currentColor" stroke-width="2"/>
            </svg>
          </button>
        </div>

        <div class="preview-info">
          <span>{{ currentPreviewIndex + 1 }} / {{ previewImages.length }}</span>
          <span v-if="currentPreviewImage?.description">{{ currentPreviewImage.description }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { Notify } from '@opentiny/vue'

// Props
interface Props {
  targetId: number
  targetType: 'activity' | 'diary' | 'media'
  allowComment?: boolean
  maxLevel?: number
  pageSize?: number
}

const props = withDefaults(defineProps<Props>(), {
  allowComment: true,
  maxLevel: 3,
  pageSize: 20
})

// Emits
const emit = defineEmits<{
  commentAdded: [comment: any]
  commentDeleted: [commentId: number]
  commentLiked: [comment: any]
}>()

// 响应式数据
const comments = ref<any[]>([])
const totalComments = ref(0)
const currentPage = ref(1)
const hasMore = ref(true)
const loading = ref(false)
const isSubmitting = ref(false)

const newComment = ref('')
const replyTarget = ref<any>(null)
const highlightCommentId = ref<number | null>(null)

const sortBy = ref('newest')
const onlyShowImages = ref(false)

// 表情和交互
const showEmojiPicker = ref(false)
const activeCategory = ref('smile')
const showMentions = ref(false)
const mentionSuggestions = ref<any[]>([])

const activeCommentMenu = ref<number | null>(null)
const expandedReplies = ref(new Set<number>())

// 图片预览
const showImagePreview = ref(false)
const currentPreviewImage = ref<any>(null)
const currentPreviewIndex = ref(0)
const previewImages = ref<any[]>([])

// 当前用户
const currentUser = ref({
  id: 1,
  name: '我',
  avatar: '/images/avatars/current-user.jpg'
})

// 输入框引用
const commentInputRef = ref<HTMLTextAreaElement>()

// 表情分类
const emojiCategories = [
  { name: 'smile', icon: '😊', emojis: ['😊', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😇', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😜', '🤪', '😝', '🤑', '🤗', '🤭', '🤫', '🤔'] },
  { name: 'emotion', icon: '❤️', emojis: ['❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❣️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '💟'] },
  { name: 'hand', icon: '👍', emojis: ['👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆', '👇', '☝️', '✋', '🤚', '🖐️', '🖖', '👋', '🤏', '✊', '👊', '🤛', '🤜', '👏', '🙌', '👐', '🤲'] }
]

// 快速表情回应
const quickReactions = [
  { emoji: '👍', label: '赞' },
  { emoji: '❤️', label: '爱' },
  { emoji: '😂', label: '哈哈' },
  { emoji: '😮', label: '哇' },
  { emoji: '😢', label: '伤心' },
  { emoji: '😡', label: '愤怒' }
]

// 计算属性
const currentEmojis = computed(() => {
  const category = emojiCategories.find(cat => cat.name === activeCategory.value)
  return category ? category.emojis : []
})

const filteredComments = computed(() => {
  let filtered = [...comments.value]

  if (onlyShowImages.value) {
    filtered = filtered.filter(comment =>
      comment.images && comment.images.length > 0
    )
  }

  // 排序
  filtered.sort((a, b) => {
    switch (sortBy.value) {
      case 'oldest':
        return new Date(a.createTime).getTime() - new Date(b.createTime).getTime()
      case 'hottest':
        return (b.likeCount || 0) - (a.likeCount || 0)
      case 'newest':
      default:
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
    }
  })

  return filtered
})

// 方法
const handleInput = () => {
  // 处理@用户功能
  const cursorPosition = commentInputRef.value?.selectionStart || 0
  const textBeforeCursor = newComment.value.substring(0, cursorPosition)
  const atMatch = textBeforeCursor.match(/@([^@\s]*)$/)

  if (atMatch) {
    showMentions.value = true
    searchMentionUsers(atMatch[1])
  } else {
    showMentions.value = false
  }
}

const searchMentionUsers = async (keyword: string) => {
  // 模拟搜索用户
  mentionSuggestions.value = [
    { id: 1, name: '张小明', avatar: '', relation: '家庭成员' },
    { id: 2, name: '李小红', avatar: '', relation: '朋友' },
    { id: 3, name: '王大华', avatar: '', relation: '同事' }
  ].filter(user => user.name.includes(keyword))
}

const insertEmoji = (emoji: string) => {
  const cursorPosition = commentInputRef.value?.selectionStart || 0
  const textBefore = newComment.value.substring(0, cursorPosition)
  const textAfter = newComment.value.substring(cursorPosition)

  newComment.value = textBefore + emoji + textAfter

  nextTick(() => {
    if (commentInputRef.value) {
      const newPosition = cursorPosition + emoji.length
      commentInputRef.value.setSelectionRange(newPosition, newPosition)
      commentInputRef.value.focus()
    }
  })

  showEmojiPicker.value = false
}

const insertMention = (user: any) => {
  const cursorPosition = commentInputRef.value?.selectionStart || 0
  const textBeforeCursor = newComment.value.substring(0, cursorPosition)
  const textAfterCursor = newComment.value.substring(cursorPosition)

  // 找到@符号的位置
  const atIndex = textBeforeCursor.lastIndexOf('@')
  const textBeforeAt = textBeforeCursor.substring(0, atIndex)

  newComment.value = textBeforeAt + `@${user.name} ` + textAfterCursor

  nextTick(() => {
    if (commentInputRef.value) {
      const newPosition = atIndex + user.name.length + 2
      commentInputRef.value.setSelectionRange(newPosition, newPosition)
      commentInputRef.value.focus()
    }
  })

  showMentions.value = false
}

const submitComment = async () => {
  if (!newComment.value.trim() || isSubmitting.value) return

  try {
    isSubmitting.value = true

    // 模拟提交评论
    await new Promise(resolve => setTimeout(resolve, 1000))

    const comment = {
      id: Date.now(),
      content: newComment.value.trim(),
      createTime: new Date().toISOString(),
      likeCount: 0,
      isLiked: false,
      user: currentUser.value,
      replies: [],
      parentId: replyTarget.value?.id || null
    }

    if (replyTarget.value) {
      // 添加到回复列表
      const parentComment = comments.value.find(c => c.id === replyTarget.value.id)
      if (parentComment) {
        if (!parentComment.replies) parentComment.replies = []
        parentComment.replies.push(comment)
        expandedReplies.value.add(parentComment.id)
      }
    } else {
      // 添加到主评论列表
      comments.value.unshift(comment)
    }

    totalComments.value++

    clearInput()

    Notify({
      type: 'success',
      message: '评论发表成功',
      position: 'top-right'
    })

    emit('commentAdded', comment)

  } catch (error) {
    console.error('Submit comment failed:', error)
    Notify({
      type: 'error',
      message: '评论发表失败，请重试',
      position: 'top-right'
    })
  } finally {
    isSubmitting.value = false
  }
}

const clearInput = () => {
  newComment.value = ''
  replyTarget.value = null
  showEmojiPicker.value = false
  showMentions.value = false
}

const cancelReply = () => {
  replyTarget.value = null
}

const replyToComment = (comment: any, reply?: any) => {
  replyTarget.value = reply || comment
  nextTick(() => {
    commentInputRef.value?.focus()
  })
  activeCommentMenu.value = null
}

const toggleCommentLike = async (comment: any) => {
  try {
    // 模拟点赞API
    await new Promise(resolve => setTimeout(resolve, 300))

    comment.isLiked = !comment.isLiked
    comment.likeCount += comment.isLiked ? 1 : -1

    emit('commentLiked', comment)

  } catch (error) {
    console.error('Toggle like failed:', error)
  }
}

const toggleReplyLike = async (reply: any) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))

    reply.isLiked = !reply.isLiked
    reply.likeCount = (reply.likeCount || 0) + (reply.isLiked ? 1 : -1)

  } catch (error) {
    console.error('Toggle reply like failed:', error)
  }
}

const addReaction = async (comment: any, emoji: string) => {
  try {
    if (!comment.reactions) comment.reactions = {}
    if (!comment.userReaction) {
      comment.userReaction = emoji
      comment.reactions[emoji] = (comment.reactions[emoji] || 0) + 1
    } else if (comment.userReaction === emoji) {
      comment.reactions[emoji] = Math.max(0, comment.reactions[emoji] - 1)
      comment.userReaction = null
    } else {
      comment.reactions[comment.userReaction] = Math.max(0, comment.reactions[comment.userReaction] - 1)
      comment.userReaction = emoji
      comment.reactions[emoji] = (comment.reactions[emoji] || 0) + 1
    }
  } catch (error) {
    console.error('Add reaction failed:', error)
  }
}

const toggleCommentMenu = (comment: any) => {
  activeCommentMenu.value = activeCommentMenu.value === comment.id ? null : comment.id
}

const copyComment = (comment: any) => {
  navigator.clipboard.writeText(comment.content)
  Notify({
    type: 'success',
    message: '评论内容已复制',
    position: 'top-right'
  })
  activeCommentMenu.value = null
}

const deleteComment = async (comment: any) => {
  if (!confirm('确定要删除这条评论吗？')) return

  try {
    // 模拟删除API
    await new Promise(resolve => setTimeout(resolve, 500))

    comment.isDeleted = true
    comment.content = ''

    Notify({
      type: 'success',
      message: '评论已删除',
      position: 'top-right'
    })

    emit('commentDeleted', comment.id)

  } catch (error) {
    console.error('Delete comment failed:', error)
    Notify({
      type: 'error',
      message: '删除失败，请重试',
      position: 'top-right'
    })
  } finally {
    activeCommentMenu.value = null
  }
}

const reportComment = (comment: any) => {
  // 模拟举报功能
  Notify({
    type: 'info',
    message: '举报已提交，我们会尽快处理',
    position: 'top-right'
  })
  activeCommentMenu.value = null
}

const toggleReplies = (commentId: number) => {
  if (expandedReplies.value.has(commentId)) {
    expandedReplies.value.delete(commentId)
  } else {
    expandedReplies.value.add(commentId)
  }
}

const loadMoreComments = async () => {
  if (loading.value || !hasMore.value) return

  try {
    loading.value = true
    currentPage.value++

    // 模拟加载更多评论
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 这里应该调用API加载更多评论
    // const response = await commentApi.getComments(props.targetId, currentPage.value)

  } catch (error) {
    console.error('Load more comments failed:', error)
  } finally {
    loading.value = false
  }
}

const handleSortChange = () => {
  // 重新排序评论
}

const previewImage = (image: any, images: any[]) => {
  currentPreviewImage.value = image
  previewImages.value = images
  currentPreviewIndex.value = images.indexOf(image)
  showImagePreview.value = true
}

const closeImagePreview = () => {
  showImagePreview.value = false
  currentPreviewImage.value = null
  previewImages.value = []
}

const previousImage = () => {
  if (currentPreviewIndex.value > 0) {
    currentPreviewIndex.value--
    currentPreviewImage.value = previewImages.value[currentPreviewIndex.value]
  }
}

const nextImage = () => {
  if (currentPreviewIndex.value < previewImages.value.length - 1) {
    currentPreviewIndex.value++
    currentPreviewImage.value = previewImages.value[currentPreviewIndex.value]
  }
}

const formatTime = (timestamp: string): string => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
  const diffMinutes = Math.floor(diffTime / (1000 * 60))

  if (diffDays > 0) {
    return `${diffDays}天前`
  } else if (diffHours > 0) {
    return `${diffHours}小时前`
  } else if (diffMinutes > 0) {
    return `${diffMinutes}分钟前`
  } else {
    return '刚刚'
  }
}

const formatCommentContent = (content: string): string => {
  // 处理@用户、链接、表情等
  return content
    .replace(/@(\w+)/g, '<span class="mention">@$1</span>')
    .replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>')
}

// 生命周期
onMounted(() => {
  // 初始化评论数据
  comments.value = [
    {
      id: 1,
      content: '这个活动很棒！期待和大家一起度过愉快的时光。😊',
      createTime: '2024-01-22T14:30:00',
      likeCount: 3,
      isLiked: false,
      user: {
        id: 2,
        name: '李小红',
        avatar: '/images/avatars/user2.jpg'
      },
      replies: []
    },
    {
      id: 2,
      content: '我会准时参加的，有什么需要帮忙准备的吗？',
      createTime: '2024-01-22T16:45:00',
      likeCount: 1,
      isLiked: true,
      user: {
        id: 3,
        name: '王大华',
        avatar: '/images/avatars/user3.jpg'
      },
      replies: []
    }
  ]
  totalComments.value = comments.value.length

  // 点击外部关闭菜单
  document.addEventListener('click', () => {
    activeCommentMenu.value = null
    showEmojiPicker.value = false
    showMentions.value = false
  })
})

onUnmounted(() => {
  document.removeEventListener('click', () => {})
})
</script>

<style lang="scss" scoped>
.comment-system {
  .comment-input-section {
    margin-bottom: 2rem;

    .comment-input-container {
      display: flex;
      gap: 1rem;
      background: white;
      padding: 1.5rem;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

      .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .avatar-placeholder {
          width: 100%;
          height: 100%;
          background: #e5e7eb;
          color: #6b7280;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
        }
      }

      .input-wrapper {
        flex: 1;

        .input-area {
          position: relative;

          .comment-textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 0.9rem;
            line-height: 1.5;
            resize: vertical;
            min-height: 80px;

            &:focus {
              outline: none;
              border-color: #3b82f6;
              box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }

            &::placeholder {
              color: #9ca3af;
            }
          }

          .input-tools {
            position: relative;

            .emoji-picker {
              position: relative;

              .tool-btn {
                position: absolute;
                bottom: 0.75rem;
                right: 0.75rem;
                width: 32px;
                height: 32px;
                border: none;
                background: none;
                color: #6b7280;
                cursor: pointer;
                border-radius: 6px;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s ease;

                &:hover {
                  background: #f3f4f6;
                  color: #374151;
                }

                svg {
                  width: 18px;
                  height: 18px;
                }
              }

              .emoji-panel {
                position: absolute;
                bottom: 100%;
                right: 0;
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                width: 300px;
                z-index: 10;

                .emoji-categories {
                  display: flex;
                  border-bottom: 1px solid #f1f5f9;

                  .category-btn {
                    flex: 1;
                    padding: 0.75rem;
                    border: none;
                    background: none;
                    cursor: pointer;
                    transition: background 0.2s ease;

                    &:hover {
                      background: #f9fafb;
                    }

                    &.active {
                      background: #eff6ff;
                      color: #3b82f6;
                    }
                  }
                }

                .emoji-grid {
                  display: grid;
                  grid-template-columns: repeat(6, 1fr);
                  gap: 0.25rem;
                  padding: 0.75rem;
                  max-height: 200px;
                  overflow-y: auto;

                  .emoji-btn {
                    width: 36px;
                    height: 36px;
                    border: none;
                    background: none;
                    cursor: pointer;
                    border-radius: 6px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 1.2rem;
                    transition: background 0.2s ease;

                    &:hover {
                      background: #f3f4f6;
                    }
                  }
                }
              }
            }

            .mention-users {
              .mention-list {
                position: absolute;
                bottom: 100%;
                left: 0;
                right: 0;
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                max-height: 200px;
                overflow-y: auto;
                z-index: 10;

                .mention-item {
                  display: flex;
                  align-items: center;
                  gap: 0.75rem;
                  padding: 0.75rem;
                  cursor: pointer;
                  transition: background 0.2s ease;

                  &:hover {
                    background: #f9fafb;
                  }

                  .mention-avatar {
                    width: 32px;
                    height: 32px;
                    border-radius: 50%;
                    overflow: hidden;

                    img {
                      width: 100%;
                      height: 100%;
                      object-fit: cover;
                    }

                    .avatar-placeholder {
                      width: 100%;
                      height: 100%;
                      background: #e5e7eb;
                      color: #6b7280;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      font-weight: 600;
                      font-size: 0.8rem;
                    }
                  }

                  .mention-info {
                    .mention-name {
                      font-weight: 500;
                      color: #374151;
                    }

                    .mention-relation {
                      font-size: 0.8rem;
                      color: #6b7280;
                    }
                  }
                }
              }
            }
          }
        }

        .input-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 0.75rem;

          .input-stats {
            display: flex;
            align-items: center;
            gap: 1rem;
            font-size: 0.8rem;
            color: #9ca3af;

            .char-count {
              &.warning {
                color: #f59e0b;
              }
            }

            .reply-info {
              display: flex;
              align-items: center;
              gap: 0.5rem;
              color: #3b82f6;

              .cancel-reply {
                background: none;
                border: none;
                color: #6b7280;
                cursor: pointer;
                width: 18px;
                height: 18px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;

                &:hover {
                  background: #f3f4f6;
                }
              }
            }
          }

          .action-buttons {
            display: flex;
            gap: 0.75rem;

            .cancel-btn {
              padding: 0.5rem 1rem;
              border: 1px solid #d1d5db;
              background: white;
              color: #6b7280;
              border-radius: 6px;
              cursor: pointer;
              font-size: 0.85rem;
              transition: all 0.2s ease;

              &:hover {
                background: #f9fafb;
                border-color: #9ca3af;
              }
            }

            .submit-btn {
              display: flex;
              align-items: center;
              gap: 0.5rem;
              padding: 0.5rem 1rem;
              background: #3b82f6;
              color: white;
              border: none;
              border-radius: 6px;
              cursor: pointer;
              font-size: 0.85rem;
              font-weight: 500;
              transition: all 0.2s ease;

              &:hover:not(:disabled) {
                background: #2563eb;
              }

              &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
              }

              svg {
                width: 14px;
                height: 14px;
              }

              .loading-spinner {
                animation: spin 1s linear infinite;
              }
            }
          }
        }
      }
    }
  }

  .comment-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;

    .comment-stats {
      .comment-count {
        font-weight: 600;
        color: #374151;
      }
    }

    .comment-filters {
      display: flex;
      align-items: center;
      gap: 1rem;

      .sort-select {
        padding: 0.5rem;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        background: white;
        color: #374151;
        font-size: 0.85rem;

        &:focus {
          outline: none;
          border-color: #3b82f6;
        }
      }

      .filter-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 1rem;
        border: 1px solid #d1d5db;
        background: white;
        color: #6b7280;
        border-radius: 6px;
        cursor: pointer;
        font-size: 0.85rem;
        transition: all 0.2s ease;

        &:hover {
          background: #f9fafb;
          border-color: #9ca3af;
        }

        &.active {
          background: #3b82f6;
          border-color: #3b82f6;
          color: white;
        }

        svg {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .comments-container {
    .comments-list {
      display: flex;
      flex-direction: column;
      gap: 1.5rem;

      .comment-item {
        display: flex;
        gap: 1rem;
        padding: 1.5rem;
        background: white;
        border-radius: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease;

        &.is-replying {
          border: 2px solid #3b82f6;
          background: #eff6ff;
        }

        &.is-highlighted {
          background: #fef3c7;
          border: 1px solid #f59e0b;
        }

        .comment-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          flex-shrink: 0;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .avatar-placeholder {
            width: 100%;
            height: 100%;
            background: #e5e7eb;
            color: #6b7280;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
          }
        }

        .comment-content {
          flex: 1;

          .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.5rem;

            .comment-author {
              font-weight: 600;
              color: #1e293b;
            }

            .comment-time {
              font-size: 0.8rem;
              color: #9ca3af;
            }

            .comment-actions {
              position: relative;

              .action-btn {
                width: 24px;
                height: 24px;
                border: none;
                background: none;
                color: #9ca3af;
                cursor: pointer;
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s ease;

                &:hover {
                  background: #f3f4f6;
                  color: #6b7280;
                }

                svg {
                  width: 14px;
                  height: 14px;
                }
              }

              .comment-menu {
                position: absolute;
                top: 100%;
                right: 0;
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                min-width: 120px;
                overflow: hidden;
                z-index: 10;

                .menu-item {
                  display: flex;
                  align-items: center;
                  gap: 0.75rem;
                  width: 100%;
                  padding: 0.75rem 1rem;
                  border: none;
                  background: none;
                  text-align: left;
                  color: #374151;
                  cursor: pointer;
                  font-size: 0.85rem;
                  transition: background 0.2s ease;

                  &:hover {
                    background: #f3f4f6;
                  }

                  &.danger {
                    color: #ef4444;

                    &:hover {
                      background: #fef2f2;
                    }
                  }

                  svg {
                    width: 14px;
                    height: 14px;
                  }
                }
              }
            }
          }

          .comment-text {
            color: #374151;
            line-height: 1.5;
            margin-bottom: 0.75rem;
            word-wrap: break-word;

            :deep(.mention) {
              color: #3b82f6;
              font-weight: 500;
            }

            :deep(a) {
              color: #3b82f6;
              text-decoration: underline;
            }
          }

          .comment-deleted {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: #9ca3af;
            font-style: italic;
            margin-bottom: 0.75rem;

            svg {
              width: 16px;
              height: 16px;
            }
          }

          .comment-images {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 0.75rem;

            .comment-image {
              width: 80px;
              height: 80px;
              border-radius: 6px;
              overflow: hidden;
              cursor: pointer;
              transition: transform 0.2s ease;

              &:hover {
                transform: scale(1.05);
              }

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }

          .comment-interactions {
            display: flex;
            align-items: center;
            gap: 1rem;

            .interaction-btn {
              display: flex;
              align-items: center;
              gap: 0.25rem;
              padding: 0.25rem 0.5rem;
              border: none;
              background: none;
              color: #9ca3af;
              cursor: pointer;
              font-size: 0.8rem;
              border-radius: 4px;
              transition: all 0.2s ease;

              &:hover {
                color: #6b7280;
                background: #f3f4f6;
              }

              &.active {
                color: #ef4444;
              }

              svg {
                width: 14px;
                height: 14px;
              }
            }

            .quick-reactions {
              display: flex;
              gap: 0.25rem;

              .reaction-btn {
                display: flex;
                align-items: center;
                gap: 0.25rem;
                padding: 0.25rem;
                border: 1px solid #e5e7eb;
                background: white;
                border-radius: 15px;
                cursor: pointer;
                font-size: 0.8rem;
                transition: all 0.2s ease;

                &:hover {
                  background: #f9fafb;
                  border-color: #d1d5db;
                }

                &.active {
                  background: #3b82f6;
                  border-color: #3b82f6;
                  color: white;
                }
              }
            }
          }

          .replies-container {
            margin-top: 1rem;

            .replies-header {
              .toggle-replies {
                display: flex;
                align-items: center;
                gap: 0.5rem;
                padding: 0.5rem 0;
                border: none;
                background: none;
                color: #3b82f6;
                cursor: pointer;
                font-size: 0.85rem;
                font-weight: 500;

                svg {
                  width: 16px;
                  height: 16px;
                  transition: transform 0.2s ease;

                  &.rotated {
                    transform: rotate(180deg);
                  }
                }
              }
            }

            .replies-list {
              border-left: 2px solid #f1f5f9;
              margin-left: 1rem;

              .reply-item {
                display: flex;
                gap: 0.75rem;
                padding: 0.75rem 0 0.75rem 1rem;

                &:not(:last-child) {
                  border-bottom: 1px solid #f8fafc;
                }

                .reply-avatar {
                  width: 32px;
                  height: 32px;
                  border-radius: 50%;
                  overflow: hidden;
                  flex-shrink: 0;

                  img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                  }

                  .avatar-placeholder {
                    width: 100%;
                    height: 100%;
                    background: #e5e7eb;
                    color: #6b7280;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-weight: 600;
                    font-size: 0.8rem;
                  }
                }

                .reply-content {
                  flex: 1;

                  .reply-header {
                    display: flex;
                    align-items: center;
                    gap: 1rem;
                    margin-bottom: 0.25rem;

                    .reply-author {
                      font-weight: 600;
                      color: #374151;
                      font-size: 0.85rem;
                    }

                    .reply-time {
                      font-size: 0.75rem;
                      color: #9ca3af;
                    }
                  }

                  .reply-text {
                    color: #4b5563;
                    font-size: 0.85rem;
                    line-height: 1.5;
                    margin-bottom: 0.5rem;

                    :deep(.mention) {
                      color: #3b82f6;
                      font-weight: 500;
                    }
                  }

                  .reply-actions {
                    display: flex;
                    gap: 1rem;

                    .reply-action {
                      display: flex;
                      align-items: center;
                      gap: 0.25rem;
                      padding: 0.125rem 0.25rem;
                      border: none;
                      background: none;
                      color: #9ca3af;
                      cursor: pointer;
                      font-size: 0.75rem;
                      border-radius: 4px;
                      transition: all 0.2s ease;

                      &:hover {
                        color: #6b7280;
                        background: #f3f4f6;
                      }

                      &.active {
                        color: #ef4444;
                      }

                      svg {
                        width: 12px;
                        height: 12px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    .load-more-section {
      text-align: center;
      margin-top: 2rem;

      .load-more-btn {
        padding: 0.75rem 1.5rem;
        background: #f3f4f6;
        color: #6b7280;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        font-weight: 500;
        transition: all 0.2s ease;

        &:hover {
          background: #e5e7eb;
          color: #374151;
        }
      }
    }

    .loading-state {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.75rem;
      padding: 2rem;
      color: #6b7280;

      .loading-spinner {
        width: 20px;
        height: 20px;
        border: 2px solid #e5e7eb;
        border-top-color: #3b82f6;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }
    }
  }

  .empty-comments {
    text-align: center;
    padding: 3rem 2rem;
    color: #9ca3af;

    svg {
      width: 48px;
      height: 48px;
      margin-bottom: 1rem;
    }

    p {
      margin: 0;
      font-size: 1rem;
    }
  }

  .image-preview-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.9);
    z-index: 50;
    display: flex;
    align-items: center;
    justify-content: center;

    .image-preview-container {
      position: relative;
      max-width: 90vw;
      max-height: 90vh;

      .preview-close {
        position: absolute;
        top: -50px;
        right: 0;
        background: none;
        border: none;
        color: white;
        cursor: pointer;
        padding: 0.5rem;
        border-radius: 6px;
        transition: background 0.2s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.1);
        }

        svg {
          width: 24px;
          height: 24px;
        }
      }

      img {
        max-width: 100%;
        max-height: 90vh;
        border-radius: 8px;
      }

      .preview-controls {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        justify-content: space-between;
        width: 100%;
        padding: 0 2rem;

        .preview-nav {
          width: 48px;
          height: 48px;
          background: rgba(0, 0, 0, 0.6);
          border: none;
          color: white;
          border-radius: 50%;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: background 0.2s ease;

          &:hover {
            background: rgba(0, 0, 0, 0.8);
          }

          svg {
            width: 20px;
            height: 20px;
          }
        }
      }

      .preview-info {
        position: absolute;
        bottom: -50px;
        left: 50%;
        transform: translateX(-50%);
        color: white;
        text-align: center;

        span {
          display: block;
          font-size: 0.9rem;

          &:first-child {
            opacity: 0.8;
            margin-bottom: 0.25rem;
          }
        }
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .comment-system {
    .comment-input-section .comment-input-container {
      flex-direction: column;
      gap: 0.75rem;
      padding: 1rem;

      .user-avatar {
        width: 36px;
        height: 36px;
        align-self: flex-start;
      }

      .input-wrapper .input-actions {
        flex-direction: column;
        align-items: stretch;
        gap: 0.75rem;

        .input-stats {
          justify-content: center;
        }

        .action-buttons {
          justify-content: center;
        }
      }
    }

    .comment-controls {
      flex-direction: column;
      gap: 1rem;
      align-items: stretch;

      .comment-filters {
        justify-content: center;
      }
    }

    .comments-container .comments-list .comment-item {
      padding: 1rem;

      .comment-avatar {
        width: 36px;
        height: 36px;
      }

      .comment-content .comment-interactions {
        flex-wrap: wrap;
        gap: 0.75rem;

        .quick-reactions {
          order: -1;
          width: 100%;
          justify-content: center;
        }
      }
    }
  }
}
</style>
